<template>
  <div class="admin-dashboard">
    <!-- 复用管理员侧边栏 -->
    <div class="admin-sidebar">
      <div class="admin-sidebar-header">
        <h2>管理控制台</h2>
      </div>
      <ul class="admin-menu">
        <li>
          <router-link to="/admin/dashboard" class="menu-item" active-class="active">
            <span class="menu-icon">📊</span>
            <span class="menu-text">仪表盘</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/users" class="menu-item" active-class="active">
            <span class="menu-icon">👥</span>
            <span class="menu-text">用户管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/questions" class="menu-item" active-class="active">
            <span class="menu-icon">❓</span>
            <span class="menu-text">问答管理</span>
          </router-link>
        </li>
        <li>
          <router-link to="/admin/stories" class="menu-item" active-class="active">
            <span class="menu-icon">📖</span>
            <span class="menu-text">故事管理</span>
          </router-link>
        </li>
      </ul>
      <div class="admin-sidebar-footer">
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </div>
    </div>

    <!-- 管理员主内容区 -->
    <div class="admin-main-content">
      <div class="admin-header">
        <h1>故事管理</h1>
        <div class="admin-user-info">
          <span>欢迎，{{ currentUser?.username }}</span>
        </div>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索故事标题或内容"
          class="search-input"
        />
        <select v-model="categoryFilter" class="filter-select">
          <option value="all">全部分类</option>
          <option value="love">爱情</option>
          <option value="friendship">友情</option>
          <option value="family">亲情</option>
          <option value="self-growth">自我成长</option>
        </select>
      </div>

      <!-- 故事列表 -->
      <div class="stories-grid">
        <div v-for="story in filteredStories" :key="story.id" class="story-card">
          <div class="story-card-header">
            <h3 class="story-title">{{ story.title }}</h3>
            <div class="story-actions">
              <button @click="viewStory(story)" class="action-btn view-btn">查看</button>
              <button @click="featureStory(story)" class="action-btn feature-btn">
                {{ story.isFeatured ? '取消推荐' : '推荐' }}
              </button>
              <button @click="deleteStory(story.id)" class="action-btn delete-btn">删除</button>
            </div>
          </div>
          <div class="story-meta">
            <span class="author">{{ story.author }}</span>
            <span class="category" :class="`category-${story.category}`">
              {{ getCategoryText(story.category) }}
            </span>
            <span class="date">{{ formatDate(story.createdAt) }}</span>
          </div>
          <div class="story-preview">
            {{ truncateText(story.content, 100) }}
          </div>
          <div class="story-stats">
            <span class="stat">❤️ {{ story.likes }}</span>
            <span class="stat">💬 {{ story.comments }}</span>
          </div>
        </div>
      </div>
      <p v-if="filteredStories.length === 0" class="no-data">没有找到符合条件的故事</p>

      <!-- 查看故事对话框 -->
      <div v-if="showStoryModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content story-modal">
          <h3>{{ currentStory?.title }}</h3>
          <div class="story-detail">
            <div class="story-info">
              <span class="info-item">作者：{{ currentStory?.author }}</span>
              <span class="info-item">分类：{{ getCategoryText(currentStory?.category) }}</span>
              <span class="info-item">发布时间：{{ formatDate(currentStory?.createdAt) }}</span>
              <span class="info-item">推荐：{{ currentStory?.isFeatured ? '是' : '否' }}</span>
            </div>
            <div class="story-body">
              <p v-for="(paragraph, index) in currentStory?.content?.split('\n')" :key="index">
                {{ paragraph }}
              </p>
            </div>
            <div class="story-comments">
              <h4>评论 ({{ currentStory?.comments || 0 }})</h4>
              <div v-if="currentStory?.commentList && currentStory.commentList.length > 0" class="comments-list">
                <div v-for="(comment, index) in currentStory.commentList" :key="index" class="comment-item">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.author }}</span>
                    <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                  </div>
                  <div class="comment-content">
                    <p>{{ comment.content }}</p>
                  </div>
                </div>
              </div>
              <p v-else class="no-comments">暂无评论</p>
            </div>
          </div>
          <div class="modal-actions">
            <button @click="closeModal" class="cancel-btn">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userStore } from '../../stores/user'

export default {
  name: 'StoriesView',
  data() {
    return {
      stories: [],
      searchQuery: '',
      categoryFilter: 'all',
      showStoryModal: false,
      currentStory: null,
      currentUser: null
    }
  },
  computed: {
    userState() {
      const state = userStore.getState()
      return state
    },
    filteredStories() {
      let result = [...this.stories]
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(story => 
          story.title.toLowerCase().includes(query) || 
          story.content.toLowerCase().includes(query)
        )
      }
      
      // 分类过滤
      if (this.categoryFilter !== 'all') {
        result = result.filter(story => story.category === this.categoryFilter)
      }
      
      return result
    }
  },
  mounted() {
    // 检查用户是否已登录且是管理员
    this.checkAdminAccess()
    this.loadStories()
  },
  methods: {
    checkAdminAccess() {
      if (!this.userState.isAuthenticated || !this.userState.currentUser.isAdmin) {
        this.$router.push('/admin/login')
      } else {
        this.currentUser = this.userState.currentUser
      }
    },
    loadStories() {
      // 模拟从API获取故事数据
      this.stories = [
        {
          id: 1,
          title: '那段美好的初恋时光',
          author: 'storyteller',
          category: 'love',
          content: '还记得那年夏天，我们在校园的梧桐树下相遇...\n\n那是一个阳光明媚的午后，我在图书馆看书，她走过来问我旁边的座位是否有人...\n\n我们就这样相识了，开始了一段美好的初恋时光。虽然最终因为毕业而分开，但那段回忆永远珍藏在我的心中。',
          createdAt: new Date('2024-01-10T08:30:00'),
          isFeatured: true,
          likes: 128,
          comments: 24,
          commentList: [
            {
              author: 'reader1',
              content: '好感人的故事，让我想起了自己的初恋时光。',
              createdAt: new Date('2024-01-10T10:15:00')
            },
            {
              author: 'reader2',
              content: '珍惜每一段美好的相遇。',
              createdAt: new Date('2024-01-10T14:20:00')
            }
          ]
        },
        {
          id: 2,
          title: '友谊的力量',
          author: 'testuser',
          category: 'friendship',
          content: '当我人生最低谷的时候，是我的好朋友小明一直陪伴在我身边...\n\n那时候我因为工作失误被公司开除，心情极度低落，甚至有了轻生的念头。小明知道后，每天都来陪我聊天，帮我重新找回自信...\n\n后来我重新找到了工作，现在我们依然是最好的朋友。朋友是一生的财富。',
          createdAt: new Date('2024-01-08T16:45:00'),
          isFeatured: false,
          likes: 89,
          comments: 15,
          commentList: [
            {
              author: 'reader3',
              content: '真正的朋友就是在你需要的时候出现。',
              createdAt: new Date('2024-01-08T18:30:00')
            }
          ]
        },
        {
          id: 3,
          title: '妈妈的唠叨',
          author: 'memberuser',
          category: 'family',
          content: '小时候总是嫌妈妈唠叨，觉得她管得太多...\n\n直到我上了大学，离开家之后，才开始想念妈妈的唠叨。每次打电话回家，听到妈妈的声音，眼泪就忍不住流下来...\n\n现在工作了，有时间就会回家陪妈妈，听她唠叨。妈妈的唠叨，是世界上最温暖的声音。',
          createdAt: new Date('2024-01-05T12:20:00'),
          isFeatured: true,
          likes: 156,
          comments: 32,
          commentList: [
            {
              author: 'reader4',
              content: '看哭了，我也要常回家看看。',
              createdAt: new Date('2024-01-05T14:10:00')
            }
          ]
        }
      ]
    },
    truncateText(text, maxLength) {
      if (!text) return ''
      const plainText = text.replace(/\n/g, ' ')
      return plainText.length > maxLength ? plainText.substring(0, maxLength) + '...' : plainText
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleDateString('zh-CN')
    },
    getCategoryText(category) {
      const categoryMap = {
        love: '爱情',
        friendship: '友情',
        family: '亲情',
        'self-growth': '自我成长'
      }
      return categoryMap[category] || category
    },
    viewStory(story) {
      this.currentStory = story
      this.showStoryModal = true
    },
    featureStory(story) {
      story.isFeatured = !story.isFeatured
    },
    deleteStory(storyId) {
      if (confirm('确定要删除这个故事吗？相关的评论也会被删除。')) {
        this.stories = this.stories.filter(s => s.id !== storyId)
      }
    },
    closeModal() {
      this.showStoryModal = false
      this.currentStory = null
    },
    handleLogout() {
      userStore.logout()
      this.$router.push('/admin/login')
    }
  }
}
</script>

<style scoped>
/* 复用管理员侧边栏样式 */
.admin-sidebar {
  width: 250px;
  background-color: #2c3e50;
  color: white;
  padding: 20px 0;
}

.admin-sidebar-header {
  padding: 0 20px 30px;
  border-bottom: 1px solid #34495e;
}

.admin-sidebar-header h2 {
  margin: 0;
  font-size: 18px;
}

.admin-menu {
  list-style: none;
  padding: 0;
  margin: 20px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  color: #bdc3c7;
  text-decoration: none;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #34495e;
  color: white;
}

.menu-item.active {
  background-color: #4CAF50;
  color: white;
}

.menu-icon {
  margin-right: 15px;
  font-size: 18px;
}

.admin-sidebar-footer {
  padding: 20px;
  border-top: 1px solid #34495e;
  margin-top: auto;
}

.logout-btn {
  width: 100%;
  padding: 10px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

/* 管理员主内容区 */
.admin-main-content {
  flex: 1;
  padding: 20px 30px;
  overflow-y: auto;
  max-width: 100%;
  overflow-x: auto;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.admin-header h1 {
  margin: 0;
  color: #2c3e50;
}

.admin-user-info {
  color: #7f8c8d;
}

/* 筛选部分 */
.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

/* 故事卡片网格 */
.stories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.story-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.story-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.story-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.story-title {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
  flex: 1;
  margin-right: 10px;
}

.story-actions {
  display: flex;
  gap: 5px;
}

.action-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.view-btn {
  background-color: #2196f3;
  color: white;
}

.view-btn:hover {
  background-color: #1976d2;
}

.feature-btn {
  background-color: #ff9800;
  color: white;
}

.feature-btn:hover {
  background-color: #f57c00;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.story-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #7f8c8d;
}

.category {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.category-love {
  background-color: #ffebee;
  color: #c62828;
}

.category-friendship {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.category-family {
  background-color: #fff8e1;
  color: #f57f17;
}

.category-self-growth {
  background-color: #e3f2fd;
  color: #1565c0;
}

.story-preview {
  margin-bottom: 15px;
  line-height: 1.5;
  color: #555;
}

.story-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #7f8c8d;
}

.no-data {
  text-align: center;
  color: #7f8c8d;
  padding: 40px;
  grid-column: 1 / -1;
}

/* 故事详情模态框 */
.story-modal {
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
}

.story-detail {
  margin-bottom: 20px;
}

.story-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.story-body {
  margin-bottom: 30px;
  line-height: 1.8;
}

.story-body p {
  margin-bottom: 15px;
}

.story-comments h4 {
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.comment-item {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.comment-author {
  font-weight: 600;
  color: #2c3e50;
}

.comment-time {
  color: #999;
}

.comment-content {
  line-height: 1.6;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 20px;
  font-style: italic;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #f1f1f1;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}
</style>